package com.xuzimian.globaldemo.spring.springmvc.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * ResponseBodyAdvice 接口：Spring Mvc4.1 新增接口,实现这个接口的类可以修改返回值直接作为ResponseBody类型的处理器(http请求)返回值，
 * 有两种类型的处理器会将返回值直接作为ResponseBody:
 * 1.返回值类型为HttpEntity
 * 2.返回值(或处理器方法)前注释了@ResponseBody
 * <p>
 * 实现ResponseBodyAdvice 接口的类型会在相应处理器处理完成请求后被相应的ReturnValueHandler调用，ReturnValueHandler是用来处理Handler
 * 返回值的。要想让这些类生效，必须将其注册到SpringMvc的容器中：
 * 1.一种是注册到RequestMappingHandlerAdapter中。
 * 2.添加@ControllerAdvice 注解
 *
 * @program: global-demo
 * @description:
 * @author: xzm
 * @create: 2019-06-04 16:39
 **/
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<String> {
    /**
     * 该方法返回true，表示返回ResponseBody的处理器返回值她都要修改
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (returnType.getMethod().getReturnType().equals(String.class)) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        return body + "<br/> this is been modified";
    }
}